package com.ls.server.service.model.strategy.impl;

import com.ls.server.domain.ChatModel;
import com.ls.server.service.ChatModelService;
import com.ls.server.service.model.ChatModelClient;
import com.ls.server.service.model.factory.impl.OpenAIModelFactory;
import com.ls.server.service.model.strategy.ChatModelStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * OpenAI 策略实现
 */
@Service
@Slf4j
public class OpenAIModelStrategy implements ChatModelStrategy {
    
    @Autowired
    private ChatModelService chatModelService;
    
    @Autowired
    private OpenAIModelFactory modelFactory;
    
    /**
     * 客户端缓存
     */
    private final Map<Long, ChatModelClient> clientCache = new ConcurrentHashMap<>();
    
    /**
     * 发送聊天请求（同步）
     *
     * @param modelId 模型ID
     * @param prompt 提示词
     * @param options 选项
     * @return 回复内容
     */
    @Override
    public String chat(Long modelId, String prompt, Map<String, Object> options) {
        ChatModelClient client = getModelClient(modelId);
        return client.chat(prompt, options);
    }
    
    /**
     * 发送聊天请求（异步流式）
     *
     * @param modelId 模型ID
     * @param prompt 提示词
     * @param options 选项
     * @return 回复内容流
     */
    @Override
    public Flux<String> chatStream(Long modelId, String prompt, Map<String, Object> options) {
        ChatModelClient client = getModelClient(modelId);
        return client.chatStream(prompt, options);
    }
    
    /**
     * 获取客户端
     *
     * @param model 模型信息
     * @return 聊天模型客户端
     */
    @Override
    public ChatModelClient getClient(ChatModel model) {
        return modelFactory.createModel(model);
    }
    
    /**
     * 获取模型客户端（带缓存）
     *
     * @param modelId 模型ID
     * @return 聊天模型客户端
     */
    private ChatModelClient getModelClient(Long modelId) {
        return clientCache.computeIfAbsent(modelId, id -> {
            ChatModel model = chatModelService.getById(id);
            if (model == null) {
                throw new RuntimeException("模型不存在");
            }
            return getClient(model);
        });
    }
} 